package com.tank.server.handler;

import com.tank.entity.GameResource;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

public class TankServer {
	public final static ChannelGroup Channel_Group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	public static GameResource resource;

	public static void main(String[] args) throws Exception {
		new TankServer().bind(8888);
	}

	public void bind(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
					.childOption(ChannelOption.SO_KEEPALIVE, true).handler(new LoggingHandler(LogLevel.INFO))
					.childHandler(new ChildChannelHandler());

			ChannelFuture f = b.bind(port).sync();
			if (f.isSuccess()) {
				System.out.println("端口绑定成功");
			} else {

			}
			f.channel().closeFuture().sync();

		} finally {
			//
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
			ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
			// ch.pipeline().addLast(new ReadTimeoutHandler(15));
			ch.pipeline().addLast(new TankServerHandler());
		}
	}
}
